package com.example.administrator.szb.activity;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.example.administrator.szb.R;
import com.example.administrator.szb.activity.base.BaseActivity;
import com.example.administrator.szb.bean.Login;
import com.example.administrator.szb.bean.ResultBean;
import com.example.administrator.szb.bean.Yzm;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.CheckMsgUtils;
import com.example.administrator.szb.util.DialogUtil;
import com.example.administrator.szb.util.GetJsonDataUtil;
import com.example.administrator.szb.util.SharedPreferencesUtil;
import com.example.administrator.szb.util.Toasts;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.api.BasicCallback;

/**
 * Created by Administrator on 2017/9/10/010.
 */

public class LoginNewActivity extends BaseActivity {
    @Bind(R.id.login_password)
    TextView loginPassword;
    @Bind(R.id.login_yzm)
    TextView loginYzm;
    @Bind(R.id.login_password_view)
    TextView loginPasswordView;
    @Bind(R.id.login_yzm_view)
    TextView loginYzmView;
    @Bind(R.id.login_phoneNum)
    EditText loginPhoneNum;
    @Bind(R.id.login_get_password)
    EditText loginGetPassword;
    @Bind(R.id.button_login)
    Button buttonLogin;
    @Bind(R.id.login_register)
    TextView loginRegister;
    @Bind(R.id.login_forget_password)
    TextView loginForgetPassword;
    @Bind(R.id.login_get_yzm)
    TextView loginGetYzm;
    @Bind(R.id.login_back)
    ImageView loginBack;
    int time = 60;//获取验证码倒计时

    private int login_tpye = 0;//0代表密码登录，1代表验证码登录
    private List<String> login_info = new ArrayList<String>();
    private static String yzm_code = "1234" ;//获取的验证码用于比对用户输入的验证码
    private int who;//用于判断是否从没有登录的fragment跳转过来
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity_new);
        ButterKnife.bind(this);
        changeStatu(1);
        SampleApplicationLike.getActivitiesInstance().add(this);
        try{
            who = getIntent().getIntExtra("who",-1);
        }catch (Exception e){

        }

    }

    @OnClick({R.id.login_password, R.id.login_yzm, R.id.login_password_view, R.id.login_yzm_view, R.id.login_phoneNum, R.id.login_get_password, R.id.button_login, R.id.login_register, R.id.login_forget_password, R.id.login_get_yzm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login_password:
                changeStatu(login_tpye);
                break;
            case R.id.login_yzm:
                changeStatu(login_tpye);
                break;
            case R.id.login_password_view:
                break;
            case R.id.login_yzm_view:
                break;
            case R.id.login_phoneNum:
                break;
            case R.id.login_get_password:
                break;
            case R.id.button_login:
                loginSzb();
               // Toasts.show(this, "执行登录", Toast.LENGTH_SHORT);
                break;
            case R.id.login_register:
                startActivity(new Intent(this,RegisterActivity.class));
                //Toasts.show(this, "跳转注册页面", Toast.LENGTH_SHORT);
                break;
            case R.id.login_forget_password:
                startActivity(new Intent(this,ForgetPasswordActivity.class));
                // Toasts.show(this, "跳转忘记密码页面", Toast.LENGTH_SHORT);
                break;
            case R.id.login_get_yzm:
                requestYzm();
                //Toasts.show(this, "执行获取验证码", Toast.LENGTH_SHORT);
                break;
        }
    }

    /**
     * 执行验证码操作
     */
    private void requestYzm() {
        getInfo();
        if (TextUtils.isEmpty(login_info.get(0)) || login_info.get(0).length()<11){
            Toasts.show(this, "请检查手机号", Toast.LENGTH_SHORT);
        }else{
            changeYzmStatu();
            getYzm();
        }

        //loginSzb();
    }
    /**
     * 获取验证码方法
     */
    private void getYzm() {
        Map<String, String> map = new HashMap<String, String>();
        getInfo();
        map.put("tel", login_info.get(0));
        map.put("type", "2");//1代表注册验证码
        map.put("code", HttpUtil.getParam());
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, Yzm.class, URLAddress.URLBASE + URLAddress.URL_YZM, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                Yzm str = (Yzm)response;
                if (str.getResult() == 1){
                    yzm_code = "";
                    yzm_code = str.getData().getCode()+"";
                }else{
                    Toasts.show(LoginNewActivity.this, ""+str.getErr_msg(), Toast.LENGTH_SHORT);
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
    }

    /**
     * 验证码按钮状态改变60秒重新发送
     */
    private void changeYzmStatu() {
        loginGetYzm.setEnabled(false);

        final Handler handlerTimeTask = new Handler();
        handlerTimeTask.postDelayed(new Runnable() {
            @Override
            public void run() {


                if (time <= 0) {
                    loginGetYzm.setEnabled(true);
                    loginGetYzm.setText("获取验证码");
                    loginGetYzm.setTextColor(getResources().getColor(R.color.tab_choose));
                    time = 60;
                } else {
                    loginGetYzm.setText(time + "秒后重新发送");
                    loginGetYzm.setTextColor(getResources().getColor(R.color.gray66));
                    handlerTimeTask.postDelayed(this, 1000);
                }
                time--;
            }
        }, 1000);

    }


    /**
     * 执行登录
     */
    private void loginSzb() {
        //getInfo();
        try{
            boolean flag = checkInfo();
            if (flag) {
                requestLogin();
            }else{
                //requestLogin();
            }
        }catch (Exception e){

        }



    }

    /**
     * 检查一下输入框输入
     * @return
     */
    private boolean checkInfo() {
        getInfo();
        if(!CheckMsgUtils.isMobileNO(login_info.get(0))){
            DialogUtil.showSimpleDialog(this,"请检查手机格式");
        }
        else if(TextUtils.isEmpty(login_info.get(1))){
            if (login_tpye == 1) {
                DialogUtil.showSimpleDialog(this,"请输入密码");
            }else{
                DialogUtil.showSimpleDialog(this,"请输入验证码");
            }

        }else if(!login_info.get(1).equals(yzm_code) && login_tpye == 1){
            DialogUtil.showSimpleDialog(this,"验证码有误");
        }
        else{
            return true;
        }
        return false;
    }

    /**
     * 执行登录请求
     */
    private void requestLogin() {
        buttonLogin.setEnabled(false);
        DialogUtil.showIsoProgressbar(LoginNewActivity.this,"登录中");
        Map<String,String> map = new HashMap<String,String>();
        map.put("code",HttpUtil.getParam());
        map.put("tel",login_info.get(0));
        if (login_tpye == 0) {
            map.put("pass",login_info.get(1));
            map.put("type","1");
        }else{
            map.put("type","0");
        }
        String json = GetJsonDataUtil.simpleMapToJsonStr(map);
        String url = URLAddress.URLBASE+URLAddress.URL_LOGIN;
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, Login.class,URLAddress.URLBASE+URLAddress.URL_LOGIN, map,new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                Login login = (Login) response;

                if (login.getResult() == 1) {
                    login.getData().getInfo().setTel_number(login_info.get(0));
                    requestBD(login);
                    requestLoginJG(login.getData().getJpushpass());//登录极光
                    SampleApplicationLike.setUserloginInstance(login.getData());
                   // startActivity(new Intent(LoginNewActivity.this,HomeActivity.class));


                }else{
                    DialogUtil.dialog_ios.dismiss();
                    buttonLogin.setEnabled(true);
                    DialogUtil.showToast(LoginNewActivity.this,login.getErr_msg());
                    //DialogUtil.showSimpleDialog(LoginNewActivity.this,login.getErr_msg());
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                DialogUtil.dialog_ios.dismiss();
                buttonLogin.setEnabled(true);
                Toasts.show(LoginNewActivity.this, ""+error, Toast.LENGTH_SHORT);
            }
        });
    }

    private void requestLoginJG(String pass) {
        JMessageClient.login(login_info.get(0),pass, new BasicCallback() {
            @Override
            public void gotResult(int i, String s) {
                Log.e("pdf", "gotResult: "+i+"     "+ s );
            }
        });
    }

    private void requestBD(final Login login) {
        HashMap<String,String> map = new HashMap<>();
        map.put("code",HttpUtil.getParam());
        map.put("users_id",login.getData().getId()+"");
        map.put("register_id", JPushInterface.getRegistrationID(this)+"");


        map.put("service_id",""+login.getData().getId());
        String info = GetJsonDataUtil.simpleMapToJsonStr(map);
        String url = URLAddress.URLBASE + URLAddress.URL_UP_INFO;
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, ResultBean.class, url, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                ResultBean resultBean = (ResultBean) response;
                if (resultBean.getResult() == 1){
                    try {
                        //DialogUtil.showSimpleDialog(LoginNewActivity.this,"登录成功");

                        SharedPreferencesUtil.savaData(LoginNewActivity.this,login.getData(),SampleApplicationLike.getKey());
                        //
//                        Intent intent = new Intent(LoginNewActivity.this,HomeActivity.class);
//                        intent.putExtra("CODE",FragmentsFlag.Activity_Login.ordinal());
//                        startActivity(intent);
                        DialogUtil.dialog_ios.dismiss();
                       finish();
                    }catch (Exception e){
                        DialogUtil.showSimpleDialog(LoginNewActivity.this,e.toString());
                    }
                }else{
                    Toasts.show(LoginNewActivity.this, ""+resultBean.getErr_msg(), Toast.LENGTH_SHORT);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
    }

    /**
     * 获取输入框信息
     */
    private void getInfo() {
        String phoneNum = loginPhoneNum.getText().toString().trim();
        String pass_or_yzm = loginGetPassword.getText().toString().trim();

        login_info.clear();
        login_info.add(phoneNum);
        login_info.add(pass_or_yzm);
    }


    /**
     * 修改切换状态
     * @param
     */
    private void changeStatu(int type) {
        if (type == 1) {
            loginPassword.setTextColor(getResources().getColor(R.color.tab_choose));
            loginPasswordView.setVisibility(View.VISIBLE);
            loginGetYzm.setVisibility(View.INVISIBLE);
            loginForgetPassword.setVisibility(View.VISIBLE);
            loginGetPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            loginGetPassword.setText("");
            //loginGetPassword.setHint("请输入验证码");

            loginYzm.setTextColor(getResources().getColor(R.color.toolbar_home));
            loginYzmView.setVisibility(View.INVISIBLE);
            loginGetPassword.setHint("请输入密码");
            login_tpye = 0;

        } else if (type == 0) {
            loginPassword.setTextColor(getResources().getColor(R.color.toolbar_home));
            loginPasswordView.setVisibility(View.INVISIBLE);
            loginGetYzm.setVisibility(View.VISIBLE);
            loginForgetPassword.setVisibility(View.INVISIBLE);
            loginGetPassword.setInputType(InputType.TYPE_CLASS_NUMBER);
            loginGetPassword.setHint("请输入验证码");
            loginGetPassword.setText("");
            loginYzm.setTextColor(getResources().getColor(R.color.tab_choose));
            loginYzmView.setVisibility(View.VISIBLE);

            loginGetPassword.setHint("请输入验证码");
            login_tpye = 1;
        }
    }

    @OnClick(R.id.login_back)
    public void onViewClicked() {
        startActivity(new Intent(this,HomeActivity.class));
       // Toasts.show(this, "执行退出登录页面", Toast.LENGTH_SHORT);
    }

    @Override
    public void onBackPressed() {
        startActivity(new Intent(this,HomeActivity.class));


        //super.onBackPressed();
    }
}
